package com.tanhua.dubbo.api;

import com.tanhua.dubbo.api.mongo.MovementApi;
import com.tanhua.dubbo.async.TimeLineService;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.vo.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 圈子-服务提供者接口实现类
 */
@DubboService
@Slf4j
public class MovementApiImpl implements MovementApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private TimeLineService timeLineService;

    /**
     * 动态-发布
     */
    @Override
    public void publish(Movement movement) {
        Long userId = movement.getUserId();//发布动态者用户id
        Long nowTime = System.currentTimeMillis();
        //1.往动态表保存动态记录
        //movement.setId(ObjectId.get());
        movement.setPid(idWorker.getNextId("movement"));//推荐系统pid 自增
        movement.setCreated(nowTime);//发布动态时间
        mongoTemplate.insert(movement);
        //2.根据当前用户id查询好友表获取好友数据
        //第三步：调用异步处理类
        timeLineService.saveTimeLine(nowTime, userId, movement.getId());
        log.debug("******userId****{}********movement{}***************", userId, movement.toString());
        /*Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        //3.循环遍历好友数据，往好友时间线表插入数据
        if(!CollectionUtils.isEmpty(friendList)){
            for (Friend friend : friendList) {
                MovementTimeLine movementTimeLine = new MovementTimeLine();
                movementTimeLine.setMovementId(movement.getId());//直接从保存动态对象中获取即可
                movementTimeLine.setUserId(userId);//发布动态的用户id
                movementTimeLine.setFriendId(friend.getFriendId());//好友id
                movementTimeLine.setCreated(nowTime);//时间
                mongoTemplate.insert(movementTimeLine);
            }
        }*/
    }

    /**
     * 根据分页参数以及userId 分页查询动态发布表
     *
     * @param page
     * @param pageSize
     * @param currendUserId
     * @return
     */
    @Override
    public PageResult<Movement> findPageByUserId(Long page, Long pageSize, Long currendUserId) {
        //定义返回PageResult<RecommendUser>
        PageResult<Movement> pageResult = new PageResult<>();
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(currendUserId));
        //1查询总记录数
        long counts = mongoTemplate.count(query, Movement.class);
        long start = (page - 1) * pageSize;
        //2查询当前页面需要展示的数据
        List<Movement> movementList = new ArrayList<>();
        if (counts > start) { //20 > 27
            //构造分页limit 0,3
            query.limit(pageSize.intValue());//每页查询几条
            query.skip(start);//跳过1条数据
            //query.with(PageRequest.of(page-1,pageSize));
            query.with(Sort.by(Sort.Direction.DESC, "created"));
            movementList = mongoTemplate.find(query, Movement.class);
        }
        return new PageResult<>(page, pageSize, counts, movementList);
    }

    /**
     * 根据用户id分页查询好有时间线数据 再查询动态表
     *
     * @param page
     * @param pageSize
     * @param userId
     * @return
     */
    @Override
    public PageResult<Movement> findFriendMovements(Long page, Long pageSize, Long userId) {
        //1.根据userId与分页参数 分页查询总记录数 好友时间线表
        Query query = new Query();
        query.addCriteria(Criteria.where("friendId").is(userId));
        long counts = mongoTemplate.count(query, MovementTimeLine.class);
        //2.根据userId与分页参数 分页查询好友时间线表数据
        long start = (page - 1) * pageSize;
        //2查询当前页面需要展示的数据
        List<MovementTimeLine> movementTimeLines = new ArrayList<>();
        if (counts > start) { //20 > 27
            //构造分页limit 0,3
            query.limit(pageSize.intValue());//每页查询几条
            query.skip(start);//跳过1条数据
            //query.with(PageRequest.of(page,pageSize));
            query.with(Sort.by(Sort.Direction.DESC, "created"));
            movementTimeLines = mongoTemplate.find(query, MovementTimeLine.class);
        }
        //3.获取所有动态ids集合 再查询动态表集合数据
        List<ObjectId> movementIds = movementTimeLines.stream().map(MovementTimeLine::getMovementId).collect(Collectors.toList());
        //List<ObjectId> movementIds = CollUtil.getFieldValues(movementTimeLines, "movementId", ObjectId.class);

        Query movementQuery = new Query();
        movementQuery.addCriteria(Criteria.where("id").in(movementIds));
        movementQuery.with(Sort.by(Sort.Direction.DESC, "created"));
        List<Movement> movementList = mongoTemplate.find(movementQuery, Movement.class);
        //4.构造pageResult对象进行返回
        return new PageResult<>(page, pageSize, counts, movementList);
    }

    /**
     * 随机产生10个动态记录
     *
     * @return
     */
    @Override
    public List<Movement> randomMovement() {
        Query query = new Query();
        long count = mongoTemplate.count(query, Movement.class);
        query.with(Sort.by(Sort.Direction.DESC, "created"));
        if (count < 10) {
            return mongoTemplate.find(query,Movement.class);
        } else {
            //count = 10
            Long start = RandomUtils.nextLong(0,count-9);
            query.skip(start).limit(10);
            return mongoTemplate.find(query,Movement.class);
        }
    }

    /**
     * 根据推荐系统写入redis的Pids查询动态数据
     *
     * @param listPids
     * @return
     */
    @Override
    public List<Movement> findByPids(List<Long> listPids) {
        Query query = new Query();
        query.addCriteria(Criteria.where("pid").in(listPids));
        query.with(Sort.by(Sort.Direction.DESC, "created"));
        return mongoTemplate.find(query,Movement.class);
    }

    /**
     * 单条动态查询
     */
    @Override
    public Movement findById(String movementId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(new ObjectId(movementId)));
        return mongoTemplate.findOne(query,Movement.class);
    }
}
